<?php

require_once 'utils.inc';

class Cookie
{
	///If expirePeriodMin=0, the cookie will expire at the end of the session (when the browser closes)
	
   function __construct($name, $expirePeriodMin=0, $path='/') 
   {
      $this->name = $name;
      $this->expMin = $expirePeriodMin;
      $this->path = $path;
      assert(!empty($this->name));
   }

	public function set() 
	{
		if (!setcookie(
					$this->name,
					$this->getValue(),
					$this->expMin ? (time() + $this->expMin * 60) : 0,
					$this->path) ) 
		{
			throw new Exception(
				"Cann't set cookie [$this->name]. There was output before?"
			);
		}
	}

	static function retrieve($name) 
	{
		if (isset($_COOKIE[$name])) {
			$c = new Cookie($name);
			$c->setValue($_COOKIE[$name]);
			return $c;
		}
		return false;
	}

   public function setExpirePeriod($min) {
      $this->expMin = $min;
   }

   public function setParam($nm, $val) {
      $this->params[$nm] = $val;
   }

   public function getParam($nm) {
      assert(isset($this->params[$nm]));
      return $this->params[$nm];
   }

   public function delete() 
   {
      $saveExp = $this->expMin;
      $this->expMin = -60;
      $this->set();
      $this->expMin = $saveExp;
   }

   public function __toString() {
      return $this->getValue();
   }


   private function getValue() {
      return implode_assoc($this->params);
   }

   private function setValue($sVal) {
      $this->params = explode_assoc($sVal);
   }

   private $name = '';
   private $expMin = 0;
   private $path = '/';
   private $params = array();
};

?>